<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>清晰账本 - 添加交易</title>
    <link rel="stylesheet" href="glassmorphism.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Arial', sans-serif;
        }
        
        body {
            background: linear-gradient(45deg, #6a11cb, #2575fc);
            min-height: 100vh;
            padding: 20px;
            color: #fff;
            padding-bottom: 80px;
        }
        
        .app-container {
            max-width: 480px;
            margin: 0 auto;
        }
        
        .header {
            display: flex;
            align-items: center;
            margin-bottom: 30px;
            position: relative;
        }
        
        .close-button {
            position: absolute;
            left: 0;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .page-title {
            flex: 1;
            text-align: center;
            font-size: 20px;
        }
        
        .save-button {
            position: absolute;
            right: 0;
            padding: 8px 15px;
            border-radius: 20px;
            background: rgba(38, 222, 129, 0.2);
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .save-button:hover {
            background: rgba(38, 222, 129, 0.3);
        }
        
        .transaction-type {
            display: flex;
            margin-bottom: 25px;
            border-radius: 20px;
            overflow: hidden;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .type-option {
            flex: 1;
            padding: 15px 0;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .type-option.active {
            background: rgba(255, 255, 255, 0.2);
        }
        
        .expense-option {
            color: #ff5e62;
        }
        
        .income-option {
            color: #26de81;
        }
        
        .form-card {
            border-radius: 24px;
            padding: 25px;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            margin-bottom: 25px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group:last-child {
            margin-bottom: 0;
        }
        
        .form-label {
            display: block;
            font-size: 14px;
            margin-bottom: 10px;
            opacity: 0.8;
        }
        
        .form-input {
            width: 100%;
            padding: 15px;
            border-radius: 12px;
            background: rgba(255, 255, 255, 0.07);
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            color: white;
            font-size: 16px;
            transition: all 0.3s;
        }
        
        .form-input::placeholder {
            color: rgba(255, 255, 255, 0.5);
        }
        
        .form-input:focus {
            background: rgba(255, 255, 255, 0.1);
            outline: none;
            border-color: rgba(255, 255, 255, 0.3);
        }
        
        .amount-input {
            font-size: 24px;
            font-weight: bold;
            text-align: center;
        }
        
        .date-input-container {
            position: relative;
        }
        
        .date-input-container i {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            opacity: 0.7;
        }
        
        .categories {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
        }
        
        .category-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            width: calc(25% - 10px);
            padding: 15px 5px;
            border-radius: 15px;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .category-item.active {
            background: rgba(255, 255, 255, 0.25);
            transform: translateY(-5px);
            border-color: rgba(255, 255, 255, 0.4);
        }
        
        .category-icon {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.15);
            margin-bottom: 8px;
        }
        
        .category-name {
            font-size: 12px;
            text-align: center;
        }
        
        .custom-keyboard {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0, 0, 0, 0.3);
            backdrop-filter: blur(10px);
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            padding: 15px;
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            transform: translateY(100%);
            transition: transform 0.3s ease;
            z-index: 200;
        }
        
        .custom-keyboard.active {
            transform: translateY(0);
        }
        
        .key {
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 15px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            cursor: pointer;
            user-select: none;
            transition: all 0.2s;
        }
        
        .key:active {
            background: rgba(255, 255, 255, 0.2);
        }
        
        .key-function {
            font-size: 16px;
        }
        
        .navigation {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            display: flex;
            justify-content: space-around;
            padding: 15px 0;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-top: 1px solid rgba(255, 255, 255, 0.2);
            z-index: 100;
        }
        
        .nav-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            color: rgba(255, 255, 255, 0.7);
            text-decoration: none;
            transition: color 0.3s;
        }
        
        .nav-item.active {
            color: #fff;
        }
        
        .add-button {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.2);
            backdrop-filter: blur(5px);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: -40px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
        }

        .date-picker {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(5px);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }

        .date-picker-content {
            width: 90%;
            max-width: 350px;
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(15px);
            border-radius: 20px;
            padding: 25px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 25px 45px rgba(0, 0, 0, 0.2);
        }

        .date-picker-header {
            font-size: 18px;
            margin-bottom: 20px;
            text-align: center;
        }

        .date-grid {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            gap: 10px;
            margin-bottom: 20px;
        }

        .date-grid-header {
            text-align: center;
            opacity: 0.8;
            font-size: 12px;
        }

        .date-cell {
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            cursor: pointer;
            transition: all 0.3s;
        }

        .date-cell:hover {
            background: rgba(255, 255, 255, 0.1);
        }

        .date-cell.active {
            background: rgba(255, 255, 255, 0.25);
        }

        .date-actions {
            display: flex;
            justify-content: space-between;
        }

        .date-button {
            padding: 10px 20px;
            border-radius: 20px;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
            width: 45%;
            text-align: center;
        }

        .date-confirm {
            background: rgba(38, 222, 129, 0.2);
        }

        .form-error {
            color: #ff5e62;
            font-size: 12px;
            margin-top: 5px;
            display: none;
        }

        .form-error.show {
            display: block;
        }

        .toast {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(38, 222, 129, 0.2);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 10px;
            padding: 15px 20px;
            color: white;
            font-size: 14px;
            opacity: 0;
            transition: opacity 0.3s;
            z-index: 1000;
        }

        .toast.show {
            opacity: 1;
        }

        .toast.error {
            background: rgba(255, 94, 98, 0.2);
        }
    </style>
</head>
<body>
    <div class="app-container">
        <div class="header">
            <a href="index.html" class="close-button">
                <i class="material-icons">close</i>
            </a>
            <div class="page-title">添加新交易</div>
            <div class="save-button" id="saveButton">保存</div>
        </div>
        
        <div class="transaction-type">
            <div class="type-option expense-option active" data-type="expense">支出</div>
            <div class="type-option income-option" data-type="income">收入</div>
        </div>
        
        <div class="form-card">
            <div class="form-group">
                <label class="form-label">金额</label>
                <input type="text" class="form-input amount-input" placeholder="0.00" id="amountInput" readonly onclick="toggleKeyboard()">
                <div id="amountError" class="form-error">请输入金额</div>
            </div>
            
            <div class="form-group">
                <label class="form-label">分类</label>
                <div class="categories expense-categories" id="expenseCategories">
                    <!-- 支出分类将通过JavaScript动态填充 -->
                </div>
                
                <div class="categories income-categories" id="incomeCategories" style="display: none;">
                    <!-- 收入分类将通过JavaScript动态填充 -->
                </div>
                <div id="categoryError" class="form-error">请选择分类</div>
            </div>
            
            <div class="form-group">
                <label class="form-label">日期</label>
                <div class="date-input-container">
                    <input type="text" class="form-input" id="dateInput" readonly onclick="toggleDatePicker()">
                    <i class="material-icons">calendar_today</i>
                </div>
            </div>
            
            <div class="form-group">
                <label class="form-label">备注</label>
                <input type="text" class="form-input" id="noteInput" placeholder="添加备注...">
            </div>
        </div>
    </div>
    
    <div class="custom-keyboard" id="customKeyboard">
        <div class="key" onclick="addNumber('1')">1</div>
        <div class="key" onclick="addNumber('2')">2</div>
        <div class="key" onclick="addNumber('3')">3</div>
        <div class="key" onclick="addNumber('4')">4</div>
        <div class="key" onclick="addNumber('5')">5</div>
        <div class="key" onclick="addNumber('6')">6</div>
        <div class="key" onclick="addNumber('7')">7</div>
        <div class="key" onclick="addNumber('8')">8</div>
        <div class="key" onclick="addNumber('9')">9</div>
        <div class="key" onclick="addNumber('.')">.</div>
        <div class="key" onclick="addNumber('0')">0</div>
        <div class="key key-function" onclick="deleteNumber()">
            <i class="material-icons">backspace</i>
        </div>
    </div>
    
    <div class="date-picker" id="datePicker">
        <div class="date-picker-content">
            <div class="date-picker-header">
                <span id="datePickerMonthYear">2023年5月</span>
            </div>
            
            <div class="date-grid" id="dateGrid">
                <!-- 日期将通过JavaScript动态填充 -->
            </div>
            
            <div class="date-actions">
                <div class="date-button" onclick="closeDatePicker()">取消</div>
                <div class="date-button date-confirm" onclick="confirmDate()">确认</div>
            </div>
        </div>
    </div>
    
    <div class="toast" id="toast">操作成功</div>
    
    <div class="navigation">
        <a href="index.html" class="nav-item">
            <i class="material-icons">home</i>
            <span>首页</span>
        </a>
        <a href="transactions.html" class="nav-item">
            <i class="material-icons">receipt_long</i>
            <span>交易</span>
        </a>
        <a href="statistics.html" class="nav-item">
            <i class="material-icons">pie_chart</i>
            <span>统计</span>
        </a>
        <a href="my_profile.html" class="nav-item">
            <i class="material-icons">person</i>
            <span>我的</span>
        </a>
    </div>
    
    <script src="app_data.js"></script>
    <script>
        // 全局变量
        let currentAmount = '';
        let selectedCategoryId = null;
        let selectedDate = new Date();
        let transactionType = 'expense';
        let editingTransactionId = null;
        
        // DOM元素
        const amountInput = document.getElementById('amountInput');
        const customKeyboard = document.getElementById('customKeyboard');
        const datePicker = document.getElementById('datePicker');
        const dateInput = document.getElementById('dateInput');
        const noteInput = document.getElementById('noteInput');
        const typeOptions = document.querySelectorAll('.type-option');
        const expenseCategories = document.getElementById('expenseCategories');
        const incomeCategories = document.getElementById('incomeCategories');
        const saveButton = document.getElementById('saveButton');
        const toast = document.getElementById('toast');
        const pageTitle = document.querySelector('.page-title');
        
        // 初始化
        function initializeApp() {
            // 检查是否是编辑模式
            const urlParams = new URLSearchParams(window.location.search);
            editingTransactionId = urlParams.get('edit');
            
            if (editingTransactionId) {
                loadTransactionForEdit();
            } else {
                // 设置当前日期
                updateDateInput();
            }
            
            // 渲染分类
            renderCategories();
            
            // 添加保存事件
            saveButton.addEventListener('click', saveTransaction);
        }
        
        // 加载要编辑的交易
        function loadTransactionForEdit() {
            const transactionManager = new window.AppData.TransactionManager();
            const transactions = transactionManager.getTransactions();
            const transaction = transactions.find(t => t.id === editingTransactionId);
            
            if (!transaction) {
                showToast('未找到交易记录', true);
                setTimeout(() => {
                    window.location.href = 'index.html';
                }, 2000);
                return;
            }
            
            // 更新页面标题
            pageTitle.textContent = '编辑交易';
            
            // 设置交易类型
            transactionType = transaction.type;
            typeOptions.forEach(option => {
                if (option.dataset.type === transactionType) {
                    option.classList.add('active');
                } else {
                    option.classList.remove('active');
                }
            });
            
            // 显示相应的分类列表
            if (transactionType === 'expense') {
                expenseCategories.style.display = 'flex';
                incomeCategories.style.display = 'none';
            } else {
                expenseCategories.style.display = 'none';
                incomeCategories.style.display = 'flex';
            }
            
            // 设置金额
            currentAmount = transaction.amount.toString();
            amountInput.value = currentAmount;
            
            // 设置分类
            selectedCategoryId = transaction.categoryId;
            
            // 设置日期
            selectedDate = new Date(transaction.date);
            updateDateInput();
            
            // 设置备注
            noteInput.value = transaction.note || '';
            
            // 在分类列表中标记选中的分类
            setTimeout(() => {
                const categoryItems = document.querySelectorAll('.category-item');
                categoryItems.forEach(item => {
                    if (item.dataset.id === selectedCategoryId) {
                        item.classList.add('active');
                    }
                });
            }, 100);
        }
        
        // 渲染分类
        function renderCategories() {
            // 渲染支出分类
            expenseCategories.innerHTML = window.AppData.expenseCategories.map(category => `
                <div class="category-item" data-id="${category.id}" onclick="selectCategory('${category.id}', 'expense')">
                    <div class="category-icon">
                        <i class="material-icons">${category.icon}</i>
                    </div>
                    <div class="category-name">${category.name}</div>
                </div>
            `).join('');
            
            // 渲染收入分类
            incomeCategories.innerHTML = window.AppData.incomeCategories.map(category => `
                <div class="category-item" data-id="${category.id}" onclick="selectCategory('${category.id}', 'income')">
                    <div class="category-icon">
                        <i class="material-icons">${category.icon}</i>
                    </div>
                    <div class="category-name">${category.name}</div>
                </div>
            `).join('');
        }
        
        // 选择分类
        function selectCategory(categoryId, type) {
            selectedCategoryId = categoryId;
            
            // 更新UI
            const container = type === 'expense' ? expenseCategories : incomeCategories;
            const categoryItems = container.querySelectorAll('.category-item');
            
            categoryItems.forEach(item => {
                if (item.dataset.id === categoryId) {
                    item.classList.add('active');
                } else {
                    item.classList.remove('active');
                }
            });
            
            // 隐藏错误提示
            document.getElementById('categoryError').classList.remove('show');
        }
        
        // 切换交易类型
        typeOptions.forEach(option => {
            option.addEventListener('click', function() {
                transactionType = this.dataset.type;
                
                // 更新UI
                typeOptions.forEach(opt => opt.classList.remove('active'));
                this.classList.add('active');
                
                // 切换分类列表
                if (transactionType === 'expense') {
                    expenseCategories.style.display = 'flex';
                    incomeCategories.style.display = 'none';
                } else {
                    expenseCategories.style.display = 'none';
                    incomeCategories.style.display = 'flex';
                }
                
                // 重置选中的分类
                selectedCategoryId = null;
                
                // 重置分类选中状态
                const categoryItems = document.querySelectorAll('.category-item');
                categoryItems.forEach(item => item.classList.remove('active'));
            });
        });
        
        // 处理自定义键盘
        function toggleKeyboard() {
            customKeyboard.classList.toggle('active');
        }
        
        function addNumber(num) {
            // 如果是小数点，且当前已有小数点，则不做任何操作
            if (num === '.' && currentAmount.includes('.')) return;
            
            // 如果已有两位小数，且不是添加小数点，则不做任何操作
            if (currentAmount.includes('.')) {
                const decimalPart = currentAmount.split('.')[1];
                if (decimalPart && decimalPart.length >= 2 && num !== '.') return;
            }
            
            // 如果当前为空且输入小数点，自动补0
            if (currentAmount === '' && num === '.') {
                currentAmount = '0.';
            } else {
                currentAmount += num;
            }
            
            updateAmountDisplay();
            
            // 隐藏错误提示
            document.getElementById('amountError').classList.remove('show');
        }
        
        function deleteNumber() {
            currentAmount = currentAmount.slice(0, -1);
            updateAmountDisplay();
        }
        
        function updateAmountDisplay() {
            if (currentAmount === '') {
                amountInput.value = '';
                amountInput.placeholder = '0.00';
            } else {
                amountInput.value = currentAmount;
            }
        }
        
        // 日期选择器
        function toggleDatePicker() {
            renderDatePicker();
            datePicker.style.display = 'flex';
        }
        
        function closeDatePicker() {
            datePicker.style.display = 'none';
        }
        
        function renderDatePicker() {
            const year = selectedDate.getFullYear();
            const month = selectedDate.getMonth();
            
            // 更新月份和年份
            document.getElementById('datePickerMonthYear').textContent = `${year}年${month + 1}月`;
            
            // 计算当月第一天是星期几
            const firstDay = new Date(year, month, 1).getDay();
            
            // 计算当月天数
            const daysInMonth = new Date(year, month + 1, 0).getDate();
            
            // 准备日历头部
            let dateGridHtml = `
                <div class="date-grid-header">日</div>
                <div class="date-grid-header">一</div>
                <div class="date-grid-header">二</div>
                <div class="date-grid-header">三</div>
                <div class="date-grid-header">四</div>
                <div class="date-grid-header">五</div>
                <div class="date-grid-header">六</div>
            `;
            
            // 添加空白单元格直到第一天
            for (let i = 0; i < firstDay; i++) {
                dateGridHtml += '<div></div>';
            }
            
            // 添加日期单元格
            const today = new Date();
            const currentDay = selectedDate.getDate();
            
            for (let day = 1; day <= daysInMonth; day++) {
                const isSelected = day === currentDay;
                const isToday = 
                    day === today.getDate() && 
                    month === today.getMonth() && 
                    year === today.getFullYear();
                
                let className = 'date-cell';
                if (isSelected) className += ' active';
                
                dateGridHtml += `
                    <div class="${className}" data-day="${day}" onclick="selectDay(${day})">
                        ${day}
                    </div>
                `;
            }
            
            document.getElementById('dateGrid').innerHTML = dateGridHtml;
        }
        
        function selectDay(day) {
            // 更新选中的日期
            selectedDate.setDate(day);
            
            // 更新UI
            const dateCells = document.querySelectorAll('.date-cell');
            dateCells.forEach(cell => {
                if (cell.dataset.day == day) {
                    cell.classList.add('active');
                } else {
                    cell.classList.remove('active');
                }
            });
        }
        
        function confirmDate() {
            updateDateInput();
            closeDatePicker();
        }
        
        function updateDateInput() {
            const options = { year: 'numeric', month: 'long', day: 'numeric' };
            dateInput.value = selectedDate.toLocaleDateString('zh-CN', options);
        }
        
        // 保存交易
        function saveTransaction() {
            // 表单验证
            if (!validateForm()) return;
            
            // 创建交易对象
            const amount = parseFloat(currentAmount);
            const transactionManager = new window.AppData.TransactionManager();
            
            if (editingTransactionId) {
                // 编辑已有交易
                const transactions = transactionManager.getTransactions();
                const existingTransaction = transactions.find(t => t.id === editingTransactionId);
                
                if (!existingTransaction) {
                    showToast('交易记录不存在', true);
                    return;
                }
                
                // 更新交易对象
                const updatedTransaction = {
                    ...existingTransaction,
                    type: transactionType,
                    amount: amount,
                    categoryId: selectedCategoryId,
                    date: selectedDate.toISOString(),
                    note: noteInput.value.trim()
                };
                
                // 保存更新后的交易
                const success = transactionManager.updateTransaction(updatedTransaction);
                
                if (success) {
                    // 显示成功提示
                    showToast('交易已更新');
                    
                    // 2秒后跳转到详情页
                    setTimeout(() => {
                        window.location.href = `transaction_detail.html?id=${editingTransactionId}`;
                    }, 1500);
                } else {
                    showToast('更新失败', true);
                }
            } else {
                // 创建新交易
                const transaction = new window.AppData.Transaction(
                    null,
                    transactionType,
                    amount,
                    selectedCategoryId,
                    selectedDate.toISOString(),
                    noteInput.value.trim()
                );
                
                // 保存交易
                transactionManager.addTransaction(transaction);
                
                // 显示成功提示
                showToast('保存成功');
                
                // 重置表单
                resetForm();
                
                // 2秒后跳转到首页
                setTimeout(() => {
                    window.location.href = 'index.html';
                }, 1500);
            }
        }
        
        // 表单验证
        function validateForm() {
            let isValid = true;
            
            // 验证金额
            if (!currentAmount || parseFloat(currentAmount) <= 0) {
                document.getElementById('amountError').classList.add('show');
                isValid = false;
            }
            
            // 验证分类
            if (!selectedCategoryId) {
                document.getElementById('categoryError').classList.add('show');
                isValid = false;
            }
            
            return isValid;
        }
        
        // 重置表单
        function resetForm() {
            currentAmount = '';
            selectedCategoryId = null;
            
            amountInput.value = '';
            noteInput.value = '';
            
            // 重置分类选中状态
            const categoryItems = document.querySelectorAll('.category-item');
            categoryItems.forEach(item => item.classList.remove('active'));
        }
        
        // 显示提示信息
        function showToast(message, isError = false) {
            toast.textContent = message;
            toast.classList.add('show');
            
            if (isError) {
                toast.classList.add('error');
            } else {
                toast.classList.remove('error');
            }
            
            setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }
        
        // 点击空白区域关闭键盘
        document.addEventListener('click', function(e) {
            if (!customKeyboard.contains(e.target) && e.target !== amountInput) {
                customKeyboard.classList.remove('active');
            }
        });
        
        // 初始化应用
        document.addEventListener('DOMContentLoaded', initializeApp);
    </script>
</body>
</html> 